package com.dazhi.show.learn.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dazhi.show.config.MyConfig;
import com.dazhi.show.core.Result;
import com.dazhi.show.core.UploadFileCacheCopyUtil;
import com.dazhi.show.learn.dao.Learn;
import com.dazhi.show.learn.server.LearnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/learn")
public class LearnController {
    @Autowired
    private LearnService learnService;
    @Resource
    private MyConfig myConfig;
    @Resource
    private UploadFileCacheCopyUtil uploadFileCacheCopyUtil;

    @GetMapping
    public Result<Page<Learn>> list(Integer current, Integer size) {
        Page<Learn> page = new Page<>(current, size);
        page.addOrder(OrderItem.desc("id"));
        Page<Learn> menuPage = learnService.page(page);
        return new Result<Page<Learn>>(200,"success",menuPage);
    }

    @GetMapping("/query")
    public Result<List<Learn>> query(Learn learn) {
        List<Learn> learnList = learnService.list(new QueryWrapper<>(learn));
        return new Result<List<Learn>>(200,"success",learnList);
    }

    @GetMapping("/{id}")
    public Result<Learn> info(@PathVariable(name="id") Integer id) {
        Learn learn = learnService.getById(id);
        return new Result<Learn>(200, "success", learn);
    }

    @PostMapping
    public Result saveOrUpdate(@RequestBody Learn learn) throws IOException {
        boolean save = learnService.saveOrUpdate(learn);
        // 取到文件名
        String path = learn.getPath();
        if (path.contains("/")) {
            // 截取文件目录
            String fileName = path.substring(path.lastIndexOf("/"));
            uploadFileCacheCopyUtil.copyTo(fileName, path);
        }
        return new Result(200, "success");
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(name="id") Integer id){
        boolean remove = learnService.removeById(id);
        return new Result(200, "success");
    }
}
